package com.ge.med.cchelper;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import com.ge.med.cchelper.listener.SaveListener;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

	boolean registeCmd = false;

	// The plug-in ID
	public static final String PLUGIN_ID = "com.ge.med.cchelper"; //$NON-NLS-1$

	// The shared instance
	private static Activator plugin;

	/**
	 * The constructor
	 */
	public Activator() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;

		Display.getDefault().asyncExec(new Runnable() {

			public void run() {
				PlatformUI.getWorkbench().getDisplay()
						.addFilter(SWT.Verify, new Listener() {
							public void handleEvent(Event event) {

								if (!registeCmd) {
									if (event.widget instanceof org.eclipse.swt.custom.StyledText) {
										System.out
												.println("register command listener");
										registeCmd = true;
										ICommandService service = (ICommandService) PlatformUI
												.getWorkbench()
												.getActiveWorkbenchWindow()
												.getService(
														ICommandService.class);
										service.addExecutionListener(new SaveListener());
									}
								}
							}
						});

			}
		});

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 * 
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}

	/**
	 * Returns an image descriptor for the image file at the given plug-in
	 * relative path
	 * 
	 * @param path
	 *            the path
	 * @return the image descriptor
	 */
	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}
}
